<template>
  <div>
    <el-form :model="form" ref="formRef" label-width="96" style="width: 100%" label-position="top">
      <el-form-item>
        <div class="model-wrap" style="width: 100%">
          <!-- 模型上传 -->
          <div class="upload-wrap">
            <p style="margin-bottom: 5px">上传模型</p>
            <el-upload
              ref="uploadModel"
              list-type="picture-card"
              v-model:file-list="modelList"
              multiple
              :auto-upload="false"
              :on-change="
                (file, fileList) => {
                  handleAvatarChangeIcon(file, fileList, 'model');
                }
              "
            >
              <div style="display: flex; flex-direction: column; align-items: center; color: #86909c">
                <el-icon class="f24"><Plus /></el-icon>
                <p class="f12" style="line-height: 22px; color: #86909c">点击上传</p>
              </div>

              <template #file="{ file }">
                <div>
                  <div
                    class="el-upload-list__item-thumbnail"
                    style="background-color: #f2f3f5; border-radius: 6px; padding: 4px 10px; box-sizing: border-box"
                  >
                    <img
                      src="@/assets/images/file.png"
                      class="ml5"
                      alt=""
                      width="50"
                      height="50"
                      style="vertical-align: bottom"
                    />
                    <span class="f12 model-name" :title="file.name">{{ file.name }}</span>
                  </div>

                  <span class="el-upload-list__item-actions">
                    <span class="el-upload-list__item-download" @click="downloadFile(file.modelUrl)">
                      <el-icon><Download /></el-icon>
                    </span>
                  </span>

                  <div class="el-upload-list__item-delete" @click="handleRemove(file)">
                    <div class="el-icon">
                      <img src="@/assets/images/del-icon.png" alt="" width="10" height="10" />
                    </div>
                  </div>
                </div>
              </template>
            </el-upload>
            <p class="f12" style="color: #86909c">
              可上传多个模型文件，如：酷家乐、三维家Sunvega、3Dmax、sketchup、fdx、skp、glb、3dm、3DS、OBJ等等
            </p>
          </div>

          <!-- 模型授权链接或型号 -->
          <div class="model-input pd16">
            <p style="margin-bottom: 5px">模型授权链接或型号</p>
            <el-input
              v-model="form.modelRemark"
              style="width: 100%"
              :rows="4"
              type="textarea"
              placeholder="方便被授权者在对应平台中快速查询到此模型，可精准的输入对应平台的链接或型号说明！"
            />
          </div>
        </div>
      </el-form-item>
    </el-form>
    <div class="dialog-footer" style="display: flex; justify-content: center">
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" :loading="btnLoading" @click="save">保存</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from "vue";
import { defineEmits } from "vue";
import useMultipartOssStore from "@/store/modules/multipartOssStore.js";
const ossStore = useMultipartOssStore();
import {
  getFolder,
  _debounce //防抖，多次频繁触发时，只执行最后一次
} from "@/utils/index";
import { Download, Plus } from "@element-plus/icons-vue";
import { imgsUpload } from "@/apis/products/specifications";
import { ElMessage } from "element-plus";
const formRef = ref();
const form = ref({});
const props = defineProps({
  formValue: { type: Object, default: () => ({}) },
  btnLoading: { type: Boolean, default: false }
});
const emit = defineEmits(["dialogVisible-false", "update-data"]);

watch(
  () => props.formValue,
  val => {
    console.log("传递过来的建模详情====", val);
    form.value = JSON.parse(JSON.stringify(val));

    //模型回显
    modelList.value = val?.modelFileList?.map(item => {
      return {
        url: item.url,
        modelUrl: item.url,
        uid: item.fileId,
        name: item.fileName
      };
    });
  },
  { deep: true }
);

const cancel = () => {
  reset();
  emit("dialogVisible-false");
};
const save = () => {
  emit("update-data", modelList.value, form.value);
};

const reset = () => {
  modelList.value = [];
  form.value.modelRemark = "";
};
defineExpose({ reset });

//====================================图片上传========================================================================================
const modelList = ref([]);
const uploadModel = ref();
const handleRemove = file => {
  uploadModel.value.handleRemove(file);
};
const handleAvatarChangeIcon = _debounce(async (file, fileList, type = "img") => {
  //选中文件触发的change事件
  console.log("触发模型上传===", file);
  let _fileList = fileList.filter(item => item.status === "ready"); //未上传成功的图片
  const flag = fileType(type, _fileList);
  if (!flag) {
    const errorFile = [];
    const successFile = [];
    if (type === "model") {
      ElMessage({
        message: "只能上传glb、gltf的模型文件或压缩文件",
        type: "error",
        offset: 60
      });
      for (let item of _fileList) {
        if (!isModelFile(item.raw.name)) {
          errorFile.push(item);
        } else {
          successFile.push(item);
        }
      }
      for (let item of errorFile) {
        uploadModel.value.handleRemove(item);
      }
    }
    if (successFile.length <= 0) return;
  }
  if (type === "model") {
    modelList.value = fileList;
    for (let item of _fileList) {
      await customUpload(item, { file: item }, type);
    }
  }
}, 100);
/**
 * 校验文件类型
 */
const fileType = (type, fileList) => {
  let flag = true;
  if (type === "img") {
    for (let item of fileList) {
      if (!(item.raw.type === "image/jpeg" || item.raw.type === "image/png")) {
        flag = false;
      }
    }
  } else if (type === "video") {
    for (let item of fileList) {
      if (!(item.raw.type === "video/mp4")) {
        flag = false;
      }
    }
  } else if (type === "model") {
    for (let item of fileList) {
      if (!isModelFile(item.raw.name)) {
        flag = false;
      }
    }
  }
  return flag;
};
const isModelFile = fileName => {
  const modelExtensions = [
    ".glb",
    ".stl",
    ".obj",
    ".fbx",
    ".gltf",
    ".dae",
    ".3ds",
    ".igs",
    ".iges",
    ".stp",
    ".step",
    ".wrl",
    ".dwg",
    ".max",
    ".blend",
    ".zip",
    ".rar",
    ".7z",
    ".tar",
    ".gzip",
    ".tgz",
    ".tar.gz",
    ".tar.bz2"
  ];
  const extension = fileName.slice(fileName.lastIndexOf(".")).toLowerCase();
  return modelExtensions.includes(extension);
};
/**
 * 上传
 */
const customUpload = async (item, option, type) => {
  // 合并已上传和当前上传文件
  const folder = getFolder();
  // const objName = folder + option.file.name;
  const objName = folder + option.file.name.split(".")[0] + new Date().getTime() + "." + option.file.name.split(".")[1];

  await ossStore
    .submit(objName, option.file.raw)
    .then(async res => {
      await ossStore.setACL(objName, fileReadRole.publicRead);
      res.fileUrl = await ossStore.signatureUrl(objName);
      item["folder"] = objName;
      item["modelUrl"] = res.fileUrl.split("?")[0];

      const Option = JSON.parse(JSON.stringify(option));
      uploadIMG(Option); //文件上传到业务端
    })
    .catch(err => {
      alert(JSON.stringify(err));
    });
};
//将图片上传到业务端服务
const uploadIMG = option => {
  const nameArr = option.file.name.split(".");
  const uploadArr = [
    {
      fileId: option.file.uid,
      objectName: "/dbo-mall" + option.file.folder, //目录＋文件名称
      url: option.file.modelUrl,
      access: "public-read",
      fileName: option.file.name, //文件名称
      bucketName: "51-jzt-dev",
      size: option.file.size,
      type: true,
      suffix: nameArr[nameArr.length - 1]
    }
  ];
  imgsUpload(uploadArr).then(res => {});
};
/**
 * 下载附件
 */
const downloadFile = url => {
  console.log("这是下载附件操作", url);
  const urlSplit = url ? url.split("/") : [];
  const name = urlSplit[urlSplit.length - 1];
  let xhr = new XMLHttpRequest();
  xhr.open("get", url, true);
  xhr.responseType = "blob";
  xhr.onload = function (e) {
    if (xhr.status === 200) {
      let file = xhr.response;
      let fileName = name;
      if ("msSaveOrOpenBlob" in navigator) {
        window.navigator.msSaveOrOpenBlob(file, fileName);
      } else {
        let fileUrl = window.URL.createObjectURL(file);
        let a = document.createElement("a");
        a.download = fileName;
        a.href = fileUrl;
        document.getElementsByTagName("body")[0].appendChild(a);
        a.click();
        a.parentNode.removeChild(a);
        window.URL.revokeObjectURL(fileUrl);
      }
    }
  };
  xhr.send();
};
const fileReadRole = {
  defaultRole: "",
  privateRole: "private",
  publicRead: "public-read",
  publicReadWrite: "public-read-write"
};
</script>

<style lang="scss" scoped>
:deep(.el-upload-list--picture-card) {
  .el-upload-list__item {
    overflow: visible !important;
  }

  .el-upload-list__item-thumbnail {
    width: 98% !important;
  }
}
p {
  padding: 0;
  margin: 0;
}
.model-name {
  word-wrap: break-word;
  line-height: 20px;
  width: 60px;
  box-sizing: border-box;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  text-transform: none;
}
:deep(.el-upload-list.el-upload-list--picture-card) {
  .el-upload-list__item-actions {
    background-color: rgba(0, 0, 0, 0.5) !important;
    background-image: none !important;
    cursor: default !important;
    display: inline-flex !important;
    font-size: 20px !important;
    height: 100% !important;
    justify-content: center !important;
    left: 0 !important;
    position: absolute !important;
    top: 0 !important;
    width: 100% !important;
    border-radius: 0 !important;
  }
  .el-upload-list__item-delete {
    opacity: 1 !important;
    display: block !important;
    top: -16px !important;
    right: -4px !important;
    position: absolute !important;
    .el-icon {
      background-color: red !important;
      border-radius: 50%;
    }
  }
  .el-upload.el-upload--picture-card {
    width: 80px;
    height: 80px;
  }
  .el-upload-list__item {
    width: 80px;
    height: 80px;
  }
}
.model-wrap {
  header {
    height: 50px;
    background-color: #f5f7fa;
    display: flex;
    align-items: center;
  }
  .upload-wrap {
    padding: 12px 16px;
  }
}
:deep(.el-form-item__label) {
  display: block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  text-align: right;
}
:deep(.warranty-label) {
  label {
    line-height: 18px;
  }
  .el-form-item__content > div .el-input__wrapper {
    box-shadow: 0 0 0 1px #f2f3f5 inset !important;
  }
  .el-form-item__label {
    white-space: wrap;
    overflow: visible;
  }
}

.del-icon {
  vertical-align: middle;
}

.model-uploader {
  :deep(.el-upload) {
    width: 100%;
    height: 80px;
    justify-content: flex-start;
    background-color: #f2f3f5;
  }
}
.buiness-address {
  :deep(.el-form-item__content) {
    display: block;
  }
}
</style>
